import 'package:flutter/material.dart';
import 'package:homepad/logger/logger.dart';
import 'package:homepad/styles.dart';

class LightBrightnessView extends StatefulWidget {
  final int max;
  final int min;
  final double step;
  final double current;
  final bool enable;

  final ValueChanged<double>? onChanged;

  const LightBrightnessView({
    super.key,
    required this.min,
    required this.max,
    required this.step,
    required this.current,
    this.onChanged,
    this.enable = true
  });

  @override
  State<LightBrightnessView> createState() {
    return _LightBrightnessView();
  }
}

class _LightBrightnessView extends State<LightBrightnessView> {
  double _offset = 50;
  double _dy = 0;
  double _target = 0;

  final height = 303.0;
  final width = 114.0;

  void setOffset(double value, {bool update = false}) {
    if (!widget.enable) {
      return;
    }
    if (value <0) {
      value = 0;
    } else if (value > height) {
      value = height;
    }

    var duration = (height - value) / height * (widget.max - widget.min);
    duration = ((duration + widget.step / 2) / widget.step).toInt().toDouble() * widget.step;
    var target = widget.min + duration;
    // 刻度值不变，也不进行页面刷新
    if (target == _target) {
      return;
    }
    if (update) {
      _target = target;
      logger.info("target: $_target");
      widget.onChanged?.call(target);
    }

    if (_offset == value) {
      return;
    }
    setState(() {
      _dy = _offset > value ? _offset - value : value - _offset;
      _offset = value;
      _lastWidget = widget;
      logger.info("offset: $_offset} dy: $_dy");
    });
  }
  LightBrightnessView? _lastWidget;

  @override
  Widget build(BuildContext context) {
    if (_lastWidget == null || _lastWidget != widget) {
      _offset = height - height * (widget.current - widget.min) / (widget.max - widget.min);
    }
    logger.info("_offset: $_offset");
    final MyStyles styles = Theme.of(context).extension<MyStyles>()!;
    return GestureDetector(
      onPanDown: (detail) => setOffset(detail.localPosition.dy),
      onPanEnd: (detail) => setOffset(detail.localPosition.dy, update: true),
      onPanStart: (detail) => setOffset(detail.localPosition.dy),
      onPanUpdate: (detail) => setOffset(detail.localPosition.dy),
      child: Container(
        width: width,
        height: height,
        decoration: BoxDecoration(
            borderRadius: styles.radius, border: styles.border, color: Colors.white10),
        child: ClipRRect(
            borderRadius: styles.radius,
            child: AnimatedPadding(
              curve: Curves.linear,
              duration: Duration(milliseconds: _dy > 10 ? 200 : 30),
              padding: EdgeInsets.only(top: _offset),
              child: Container(
                color: const Color.fromARGB(230, 255, 255, 255),
              ),
            )),
      ),
    );
  }
}
